// This is just a sample how to initialize plugins or components.
//
var Res = function(){
    var id;
    var name;
    var type;
    var iconCls;
    var pid;
    var url;
    var status;
    var des;
}

var res;

$(document).ready(function () {
    /**
     * Switchery checkbox
     * @type {HTMLElement | null}
     */
    var changeCheckbox = document.getElementById('status');
    var isEnableSwitchery = new Switchery(changeCheckbox);

    //init res Tree
    $.ajax({
        //几个参数需要注意一下
        type: "get",//方法类型
        dataType: "json",//预期服务器返回的数据类型
        url: "/system/res/getResTree",//url
        // data: ,
        success: function (result) {

            $("#res_tree").append(getRes(result))

            $("#res_tree").jstree({
                "plugins": ["search"]
            });
        },
        error: function (result) {
            bootbox.alert({
                closeButton: false,
                message: result.responseJSON.msg,
            });
        }
    })
    // select2Utils.initRemoteSelect2("loaddepart","/system/department/getDepartPage",false,"xuan")
    $("#loadRes").select2({
        ajax: {
            url: "/system/res/getResPage",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page,
                    id:$("#id").val()
                };
            },
            processResults: function (data, params) {
                // parse the results into the format expected by Select2
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data, except to indicate that infinite
                // scrolling can be used
                params.page = params.page || 1;

                return {
                    results: data.items,
                    pagination: {
                        more: (params.page * 15) < data.total_count
                    }
                };
            },
            cache: true
        },
        placeholder: '请选择上级菜单',
        allowClear: true,
        escapeMarkup: function (markup) {
            return markup;
        }, // let our custom formatter work
        // minimumInputLength: 1,
        templateResult: formatRepo,
        templateSelection: formatRepoSelection
    });

    function formatRepo(repo) {
        if (repo.loading) {
            return repo.text;
        }

        var markup = '<div href="#" data-original-title="" title=""> ' +
            '<i class="' + repo.icon + '"></i><span class="menu-title">' + repo.name + '</span><i class="arrow"></i></div>'
        return markup;
    }

    function formatRepoSelection(repo) {
        return repo.name || repo.text;
    }

    //jstree serach
    var to = false;
    $('#input-tree').keyup(function () {
        if (to) {
            clearTimeout(to);
        }
        to = setTimeout(function () {
            var v = $('#input-tree').val();
            $('#res_tree').jstree(true).search(v);
        }, 250);
    });

    $('#res_tree').bind("activate_node.jstree", function (obj, e) {
        // 处理代码
        // 获取当前节点
        var currentNode = e.node;
        if (currentNode) {
            $.ajax({
                //几个参数需要注意一下
                type: "get",//方法类型
                dataType: "json",//预期服务器返回的数据类型
                url: "/system/res/getResDetail",//url
                data: {id: currentNode.data.id},
                success: function (result) {
                    // setDepartmentInfo(result);
                    setResValue(currentNode,result);
                },
                error: function (result) {
                    bootbox.alert({
                        closeButton: false,
                        message: result.responseJSON.msg,
                    });
                }
            })
        }
    });
    /**
     * 设置department info
     * @param result
     */
    var setResInfo = function(result){
        if(!res){
            res = new Res();
        }
        res.name = result.name;
        res.id = result.id;
        res.type = result.type;
        res.iconCls = result.iconCls;
        res.status = result.status;
        res.des = result.des;
        res.url = result.url;
        res.pid = result.pid;
        res.seq = result.seq;

    }
    /**
     * 设置值
     * @param currentNode
     * @param result
     */
    var setResValue = function(currentNode,result){
    	
    	$('#res').bootstrapValidator('resetForm', false);
    	
        $("input[name='name']").val(result.name);
        $("input[name='id']").val(result.id)
        $("input[name='url']").val(result.url);
        $("input[name='iconCls']").val(result.iconCls);
        $("input[name='seq']").val(result.seq);
        $("#des").val(result.des);
        $("select[name='type']").val(result.type);
        if (result.status == 1) {
            SwitcheryUtils.setEnable(isEnableSwitchery, true)
        } else {
            SwitcheryUtils.setEnable(isEnableSwitchery, false)
        }
        // new Switchery(changeCheckbox);
        var loadRes = $('#loadRes');
        // loaddepart.empty();
        if (result.pid != 0) {
            var parentid = currentNode.parent;
            parentnode = $('#res_tree').jstree("get_node", parentid);
            loadRes.append("<option value='" + parentnode.data.id + "' selected>" + parentnode.text + "</option>");
            // loaddepart.prop("disabled", false);
            // SwitcheryUtils.setEnable(noParentSwitchery, false)
        } else {
            // var data = [{name:"a",id:1},{name:"b",id:2}];
            // select2Utils.initSelect2Value("loaddepart",data);
            // initSelect(loaddepart);
            loadRes.append("<option value='0' selected>没有上级菜单</option>");
            // loaddepart.prop("disabled", true);
            // SwitcheryUtils.setEnable(noParentSwitchery, true)
        }
        
    }


    /**
     * 提交按钮
     */
    $("#submit").on("click",function () {
    	//validate form
    	$('#res').data('bootstrapValidator').validate();
    	//if failed
    	if(!$('#res').data('bootstrapValidator').isValid()){
    		return false;
    	}

        syncResInfo();

        $.ajax({
            //几个参数需要注意一下
            type: "POST",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/system/res/addOrUpdate",//url
            // data: $('#department').serialize(),
            data:res,
            success: function (result) {
                bootbox.alert({
                    closeButton:false,
                    message:result.msg,
                    callback : function(result) {
                        //Callback function here
                        window.location.reload();
                    },
                    animateIn: 'bounceIn',
                    animateOut : 'bounceOut'
                });
            },
            error: function (result) {
                bootbox.alert({
                    closeButton: false,
                    message: result.responseJSON.msg,
                });
            }
        })
    })

    /**
     * 删除按钮
     */
    $(".btn-danger").on("click",function () {

        syncResInfo();
        
        if (!res.id) {
            bootbox.alert({
                closeButton:false,
                message:"请先选择菜单!",
                animateIn: 'bounceIn',
                animateOut : 'bounceOut'
            });
            return false;
        }
        $.ajax({
            //几个参数需要注意一下
            type: "POST",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/system/res/delete",//url
            // data: $('#department').serialize(),
            data:res,
            success: function (result) {
                bootbox.alert({
                    closeButton:false,
                    message:result.msg,
                    callback : function(result) {
                        //Callback function here
                        window.location.reload();
                    },
                    animateIn: 'bounceIn',
                    animateOut : 'bounceOut'
                });
            },
            error: function (result) {
                bootbox.alert({
                    closeButton: false,
                    message: result.responseJSON.msg,
                });
            }
        })
    })

     /**
     * 删除按钮
     */
    $(".btn-info").on("click",function () {

        $("input[name='name']").val("");
        $("input[name='id']").val("")
        $("input[name='url']").val("");
        $("input[name='iconCls']").val("");
        $("input[name='seq']").val("");
        $("#des").val("");
        $("select[name='type']").val(1);
        SwitcheryUtils.setEnable(isEnableSwitchery, true)

    })

    
    /**
     * sync department info before ajax
     */
    var syncResInfo = function(){
        if(!res){
            res = new Res();
        }
        res.name = $("input[name='name']").val();
        res.id = $("input[name='id']").val()
        res.url = $("input[name='url']").val();
        res.iconCls = $("input[name='iconCls']").val();
        res.status = changeCheckbox.checked ? 1:0;
        res.des = $("textarea[name='des']").val();
        res.pid = $("#loadRes").val()?$("#loadRes").val():0;
        res.seq = $("input[name='seq']").val()
        res.type = $("select[name='type']").val()
    }
});


 /**
 * 选中颜色
 * @param e
 */
/*function toggleSelect(e) {
    var target = $(e);
    target.toggleClass("selected");
}*/

/**
 * 展开/收起
 */
$("#nestable-menu").on("click", function (e) {
    var target = $(e.target);
    var instance = $("#res_tree").jstree(true);
    if (target.hasClass("btn-success")) {
        instance.close_all();
        target.text("展开全部");

    } else {
        target.text("收起全部");
        instance.open_all();
    }
    target.toggleClass("btn-success");
})


/**
 * 构建部门数html
 * @param res_json
 * @returns {string}
 */
var getRes = function (res_json) {
    var html = '<ul>';
    for (var i = 0, l = res_json.length; i < l; i++) {
        // for (var d in depart_json[i]) {
        html +=
            '<li data-id="' + res_json[i].id + '" data-jstree="{&quot;opened&quot;:true, &quot;icon&quot;:&quot;' + res_json[i].icon + '&quot;}">' + res_json[i].name
        //如果存在子节点
        if (res_json[i].children && res_json[i].children.length != 0) {

            html += getRes(res_json[i].children);
        }
        // }
        html += '</li>'
    }

    html += '</ul>'
    return html;
}

/**
 * 点击下拉框动态获取列表 bootstrap-select
 */
/*$('#loaddepart').on('shown.bs.select', function (e) {
    // do something...
    // console.log("do something");
    // $('#loaddepart').append("<option value='222'>请选择</option>");
    $('#loaddepart').empty();
    $.ajax({
        //几个参数需要注意一下
        type: "get",//方法类型
        dataType: "json",//预期服务器返回的数据类型
        url: "/system/department/getDepartmentList" ,//url
        // data: ,
        success: function (result) {
            var html = "";
            for(var i=0,l=result.length;i<l;i++){
                html += "<option value='"+result[i].id+"'>"+result[i].name+"</option>";
            }
            html += "<option value='0'>no thing select</option>";
            $('#loaddepart').append(html);
            $('#loaddepart').selectpicker('refresh');
        },
        error : function() {
            alert("获取部门树异常！");
        }
    })

});*/


